package server

import (
	"context"
	"errors"
	__ "fitness-srv/basic/proto"
	"fitness-srv/handler/models"
	"fitness-srv/pkg"
	"gorm.io/gorm"

	"github.com/google/uuid"
	"strconv"
	"time"
)

// server is used to implement helloworld.GreeterServer.
type Server struct {
	__.UnimplementedFitnessServer
}

// Login
func (s *Server) Login(_ context.Context, in *__.LoginReq) (*__.LoginResp, error) {
	var err error

	var user models.User
	if err = user.GetUserInfo(in.Mobile); err != nil {
		return nil, errors.New("查询失败")
	}

	if user.ID == 0 {
		user = models.User{
			Mobile:   in.Mobile,
			Password: pkg.Md5(in.Password),
		}
		if err = user.CreateUser(); err != nil {
			return nil, errors.New("注册失败")
		}
	} else {
		if user.Password != pkg.Md5(in.Password) {
			return nil, errors.New("账号密码错误")
		}
	}

	return &__.LoginResp{
		UserId: int64(user.ID),
	}, nil
}

// AddCourse
func (s *Server) AddCourse(_ context.Context, in *__.AddCourseReq) (*__.AddCourseResp, error) {
	var err error

	var user models.User
	if err = user.GetUserById(in.UserId); err != nil {
		return nil, errors.New("查询失败")
	}

	if user.ID == 0 {
		return nil, errors.New("用户不存在")
	}

	if user.UType == 1 {
		return nil, errors.New("权限不足")
	}

	straTime, err := time.Parse(time.DateTime, in.StarTime)
	if err != nil {
		return nil, errors.New("开始时间解析失败")
	}

	endTime, err := time.Parse(time.DateTime, in.EndTime)
	if err != nil {
		return nil, errors.New("结束时间解析失败")
	}

	var course models.Course
	course = models.Course{
		UserId:   int(in.UserId),
		Title:    in.Title,
		Desc:     in.Desc,
		Price:    in.Price,
		Cover:    in.Cover,
		Stock:    int(in.Stock),
		StarTime: &straTime,
		EndTime:  &endTime,
		Status:   1, //上架
	}

	if err = course.AddCourse(); err != nil {
		return nil, errors.New("课程添加失败")
	}

	return &__.AddCourseResp{
		CourseId: int64(course.ID),
	}, nil
}

// EquipmentUse
func (s *Server) EquipmentUse(_ context.Context, in *__.EquipmentUseReq) (*__.EquipmentUseResp, error) {
	var err error

	var user models.User
	if err = user.GetUserById(in.UserId); err != nil {
		return nil, errors.New("查询失败")
	}

	if user.ID == 0 {
		return nil, errors.New("用户不存在")
	}

	var equipment models.Equipment
	equipment = models.Equipment{
		UserId:   int(in.UserId),
		Name:     in.Name,
		Duration: in.Duration,
	}
	if err = equipment.AddEquipment(); err != nil {
		return nil, errors.New("器材使用登记失败")
	}

	return &__.EquipmentUseResp{
		EquipmentId: int64(equipment.ID),
	}, nil
}

// PayMember
func (s *Server) PayMember(_ context.Context, in *__.PayMemberReq) (*__.PayMemberResp, error) {
	var err error

	var user models.User
	if err = user.GetUserById(in.UserId); err != nil {
		return nil, errors.New("查询失败")
	}

	if user.ID == 0 {
		return nil, errors.New("用户不存在")
	}

	var member models.Member
	member = models.Member{
		UserId:    int(in.UserId),
		Price:     in.Price,
		PayMothed: int(in.PayMothed),
		PaySn:     uuid.NewString(),
		Lever:     int(in.Lever),
		Status:    1, //未到期
	}
	if err = member.AddMember(); err != nil {
		return nil, errors.New("会员充值失败")
	}

	return &__.PayMemberResp{
		MemberId: int64(member.ID),
		PaySn:    member.PaySn,
		PayUrl:   "",
	}, nil
}

// AddReservation
func (s *Server) AddReservation(_ context.Context, in *__.AddReservationReq) (*__.AddReservationResp, error) {
	var err error

	var user models.User
	if err = user.GetUserById(in.UserId); err != nil {
		return nil, errors.New("用户查询失败")
	}

	if user.ID == 0 {
		return nil, errors.New("用户不存在")
	}

	var course models.Course
	if err = course.GetCourseInfo(in.CourseId); err != nil {
		return nil, errors.New("课程查询失败")
	}
	if course.ID == 0 {
		return nil, errors.New("该课程不存在")
	}

	if course.Stock < int(in.Number) {
		return nil, errors.New("库存不足")
	}

	price, _ := strconv.Atoi(course.Price)

	var reservation models.Reservation
	reservation = models.Reservation{
		UserId:          int(in.UserId),
		CourserId:       int(in.CourseId),
		CoachId:         int(in.CourseId),
		EquipmentId:     int(in.EquipmentId),
		ReservationSn:   uuid.NewString(),
		Price:           float64(int(in.Number) * price),
		ReservationTime: nil,
		Number:          int(in.Number),
		Status:          1, //开始
	}
	if err = reservation.AddReservation(); err != nil {
		return nil, errors.New("预约失败")
	}

	return &__.AddReservationResp{
		ReservationId: int64(reservation.ID),
		ReservationSn: reservation.ReservationSn,
		PayUrl:        "",
	}, nil
}

// DelReservation
func (s *Server) DelReservation(_ context.Context, in *__.DelReservationReq) (*__.DelReservationResp, error) {
	var err error

	var user models.User
	if err = user.GetUserById(in.UserId); err != nil {
		return nil, errors.New("用户查询失败")
	}

	if user.ID == 0 {
		return nil, errors.New("用户不存在")
	}

	var reservation models.Reservation
	if err = reservation.GetReservation(in.ReservationId); err != nil {
		return nil, errors.New("预约查询失败")
	}

	if reservation.ID == 0 {
		return nil, errors.New("该预约不存在")
	}

	if reservation.UserId != int(in.UserId) {
		return nil, errors.New("该预约不是您的")
	}

	if err = reservation.DelReservation(in.ReservationId); err != nil {
		return nil, errors.New("取消预约失败")
	}

	return &__.DelReservationResp{}, nil
}

func (s *Server) UpdateCourse(_ context.Context, in *__.UpdateCourseReq) (*__.UpdateCourseResp, error) {
	var err error

	var user models.User
	if err = user.GetUserById(in.UserId); err != nil {
		return nil, errors.New("用户查询失败")
	}

	if user.ID == 0 {
		return nil, errors.New("用户不存在")
	}

	var course models.Course
	if err = course.GetCourseInfo(in.CourseId); err != nil {
		return nil, errors.New("课程查询失败")
	}
	if course.ID == 0 {
		return nil, errors.New("课程不存在")
	}

	if course.UserId != int(in.UserId) {
		return nil, errors.New("该课程不是您的")
	}

	course = models.Course{
		Model:  gorm.Model{ID: uint(in.CourseId)},
		UserId: int(in.UserId),
		Stock:  int(in.Num),
		Status: int(in.Status),
	}
	if err = course.UpdateCourse(in.CourseId); err != nil {
		return nil, errors.New("更新课程失败")
	}

	return &__.UpdateCourseResp{
		CourseId: int64(course.ID),
	}, nil
}

func (s *Server) GetCourseList(_ context.Context, in *__.GetCourseListReq) (*__.GetCourseListResp, error) {

	var course models.Course
	list, _ := course.GetCourseList()

	var courseList []*__.GetCourseInfo
	for _, c := range list {
		courseList = append(courseList, &__.GetCourseInfo{
			UserId: int64(c.UserId),
			Title:  c.Title,
			Desc:   c.Desc,
			Price:  c.Price,
			Stock:  int64(c.Stock),
			Cover:  c.Cover,
		})
	}

	return &__.GetCourseListResp{
		CourseList: courseList,
	}, nil
}

// GetUserDetail
func (s *Server) GetUserDetail(_ context.Context, in *__.GetUserDetailReq) (*__.GetUserDetailResp, error) {
	var err error

	var user models.User
	if err = user.GetUserById(in.UserId); err != nil {
		return nil, errors.New("用户查询失败")
	}

	if user.ID == 0 {
		return nil, errors.New("用户不存在")
	}

	return &__.GetUserDetailResp{
		Mobile:   user.Mobile,
		NickName: user.NickName,
		Sex:      int64(user.Sex),
		Height:   int64(user.Height),
		Weight:   float32(user.Weight),
		BodyFat:  user.BodyFat,
		Status:   int64(user.Status),
	}, nil
}

// GetEquipment
func (s *Server) GetEquipment(_ context.Context, in *__.GetEquipmentReq) (*__.GetEquipmentResp, error) {
	var equipment models.Equipment
	desc, _ := equipment.GetEquipmentDesc(in.Class, in.Desc)

	var equipmentList []*__.GetEquipmentDesc
	for _, e := range desc {
		equipmentList = append(equipmentList, &__.GetEquipmentDesc{
			Name:  e.Name,
			Class: e.Class,
			Desc:  e.Desc,
		})
	}

	return &__.GetEquipmentResp{
		EquipmentList: equipmentList,
	}, nil
}

// AddComment
func (s *Server) AddComment(_ context.Context, in *__.AddCommentReq) (*__.AddCommentResp, error) {
	var err error

	var coach models.Coach
	coach = models.Coach{
		Model:   gorm.Model{ID: uint(in.CoachId)},
		UserId:  int(in.UserId),
		Comment: in.Comment,
	}
	if err = coach.AddComment(in.CoachId); err != nil {
		return nil, errors.New("评论添加失败")
	}

	return &__.AddCommentResp{
		CoachId: int64(coach.ID),
	}, nil
}
